#+TITLE: dotemacs
#+AUTHOR: Piece Maker

* Begin
My Emacs config prettified into an Org file for easy documentation

This bit makes Org-mode show syntax highlighting for the Lisp in this file
#+BEGIN_SRC emacs-lisp
(setq org-src-fontify-natively t)
#+END_SRC

#+results:
: t

* Setup package manager
#+BEGIN_SRC emacs-lisp
(setq package-archives '(("marmalade" . "http://marmalade-repo.org/packages/")
			 ("melpa" . "http://melpa.org/packages/")
                         ("org" . "http://orgmode.org/elpa/")
			 ("gnu" . "http://elpa.gnu.org/packages/")))
#+END_SRC

#+results:

#+BEGIN_SRC emacs-lisp
  ;; Just in case
  (package-initialize)
#+END_SRC

* Sort out files/folder paths
Add folders to load paths
#+BEGIN_SRC emacs-lisp
(add-to-list 'load-path "/home/eddie/.elisp")
(add-to-list 'load-path "/usr/share/emacs/site-lisp/")
#+END_SRC

Put customize stuff in a seperate file to avoid screwing this one up
#+BEGIN_SRC emacs-lisp
(setq custom-file "~/.emacs.d/custom.el")
(load custom-file)
#+END_SRC

* Main Chunk
This is all the actual configgy stuff

** Small little configs
*** Dired keybinds
#+BEGIN_SRC emacs-lisp
(define-key dired-mode-map (kbd "C-, i") 'dired-subtree-insert)
(define-key dired-mode-map (kbd "C-, r") 'dired-subtree-remove)
(define-key dired-mode-map (kbd "C-, n") 'dired-subtree-narrow)
(define-key dired-mode-map (kbd "C-, <up>") 'dired-subtree-up)
(define-key dired-mode-map (kbd "C-, <down>") 'dired-subtree-down)
(define-key dired-mode-map (kbd "C-, <left>") 'dired-subtree-previous-sibling)
(define-key dired-mode-map (kbd "C-, <right>") 'dired-subtree-next-sibling)
(define-key dired-mode-map (kbd "C-, b") 'dired-subtree-beginning)
(define-key dired-mode-map (kbd "C-, e") 'dired-subtree-end)
(define-key dired-mode-map (kbd "C-, m") 'dired-subtree-mark-subtree)
(define-key dired-mode-map (kbd "C-, M") 'dired-subtree-nmark-subtree)
(define-key dired-mode-map (kbd "C-, o f") 'dired-subtree-only-this-file)
(define-key dired-mode-map (kbd "C-, o d") 'dired-subtree-only-this-directory)
(define-key dired-mode-map (kbd "C-, t") 'dired-subtree-toggle)
#+END_SRC
*** Important Unicode stoof
#+BEGIN_SRC emacs-lisp
(require 'unicode-fonts)
(setq unicode-fonts-block-font-mapping
      '(("Emoticons"
	 ("Noto Emoji" "Symbola" "Quivira"))
      ("Dingbats"
	 ("Noto Emoji" "Symbola" "Quivira"))
      ("Miscellaneous Symbols and Arrows"
         ("Noto Emoji" "Symbola" "Quivira"))
      ("Miscellaneous Symbols and Pictographs"
	 ("Noto Emoji" "Symbola" "Quivira"))
      ("Transport and Map Symbols"
	 ("Noto Emoji" "Symbola" "Quivira"))))
(unicode-fonts-setup)
#+END_SRC
*** TRAMP setting - remote/root folder manipulation
#+BEGIN_SRC emacs-lisp
(defun th-rename-tramp-buffer ()
  (when (file-remote-p (buffer-file-name))
    (rename-buffer
     (format "%s:%s"
             (file-remote-p (buffer-file-name) 'method)
             (buffer-name)))))

(add-hook 'find-file-hook
          'th-rename-tramp-buffer)

(defadvice find-file (around th-find-file activate)
  "Open FILENAME using tramp's sudo method if it's read-only."
  (if (and (not (file-writable-p (ad-get-arg 0)))
           (y-or-n-p (concat "File "
                             (ad-get-arg 0)
                             " is read-only.  Open it as root? ")))
      (th-find-file-sudo (ad-get-arg 0))
    ad-do-it))

(defun th-find-file-sudo (file)
  "Opens FILE with root privileges."
  (interactive "F")

   (set-buffer (find-file (concat "/sudo::" file))))
#+END_SRC
*** Predictive mode
#+BEGIN_SRC emacs-lisp
;; predictive install location
     (add-to-list 'load-path "~/.emacs.d/predictive/")
     ;; dictionary locations
     (add-to-list 'load-path "~/.emacs.d/predictive/latex/")
     (add-to-list 'load-path "~/.emacs.d/predictive/texinfo/")
     (add-to-list 'load-path "~/.emacs.d/predictive/html/")
     ;; load predictive package
     (autoload 'predictive-mode "~/.emacs.d/predictive/predictive"
               "Turn on Predictive Completion Mode." t)
(setq predictive-auto-learn t
      predictive-add-to-dict-ask nil
      predictive-use-auto-learn-cache nil
      predictive-which-dict t)
#+END_SRC
*** Wind Move - lets you move between windows using shift+arrow keys
#+BEGIN_SRC emacs-lisp
(when (fboundp 'windmove-default-keybindings)
  (windmove-default-keybindings))
#+END_SRC
*** Makes Emacs open in mail-mode when called from Mutt
#+BEGIN_SRC emacs-lisp
(setq auto-mode-alist
      (append
       '(("/tmp/mutt.*" . mail-mode)
         )
       auto-mode-alist)
      )
#+END_SRC
*** Different language syntax highlights
#+BEGIN_SRC emacs-lisp
(setq auto-mode-alist (cons '("\.lua$" . lua-mode) auto-mode-alist))
(autoload 'lua-mode "lua-mode" "Lua editing mode." t)

#+END_SRC
*** Create a choose browser popup for clicked URL's
#+BEGIN_SRC emacs-lisp
  (setq browse-url-browser-function 'browse-url-generic
       browse-url-generic-program "/usr/bin/firefox")
;; ;; (setq browse-url-browser-function 'xwidget-webkit-browse-url) 
 (defun choose-browser (url &rest args)
  (interactive "sURL: ")
   (if (y-or-n-p "Use external browser? ")
       (browse-url-generic url)
     (eww-browse-url url)))
   (setq browse-url-browser-function 'choose-browser)

(setq browse-url-browser-function '(("youtube" . browse-youtube-url)
                                    ("." . choose-browser)))

;; magically open youtube urls in VLC instead of browser
(defun browse-youtube-url (url &optional new-window)
  (multi-term-nvlc url))

(defun multi-term-send-string (buffer string)
  (let ((proc (get-buffer-process buffer)))
    (comint-send-string proc (format "%s\n" string))))

(defun multi-term-nvlc (url)
  (with-current-buffer (multi-term)
    (multi-term-send-string (current-buffer) (format "nvlc '%s'" url))))
#+END_SRC

*** Add PKGBUILD mode for Arch PKGBUILDs
#+BEGIN_SRC emacs-lisp
 (autoload 'pkgbuild-mode "pkgbuild-mode.el" "PKGBUILD mode." t)
 (setq auto-mode-alist (append '(("/PKGBUILD$" . pkgbuild-mode))
                               auto-mode-alist))
#+END_SRC

*** One-liners
Make titlebar represent useful info
#+BEGIN_SRC emacs-lisp
(setq frame-title-format "Emacs %b %m")
#+END_SRC
#+BEGIN_SRC emacs-lisp
(require 'epa-file)
(setq x-select-enable-clipboard t)
#+END_SRC

** Lilypond configuration
#+BEGIN_SRC emacs-lisp
;; (autoload 'Lilypond-mode "lilypond-mode")
;; (setq auto-mode-alist
;;       (cons '("\\.ly$" . LilyPond-mode) auto-mode-alist))
;; (add-hook 'find-file-hook 'auto-insert)
;; (add-hook 'LilyPond-mode-hook (lambda () (turn-on-font-lock)))
;; (setq debug-on-error t)
;; (setq locale-coding-system 'utf-8)
;; (set-terminal-coding-system 'utf-8)
;; (set-keyboard-coding-system 'utf-8)
;; (set-selection-coding-system 'utf-8)
;; (prefer-coding-system 'utf-8)
;; (add-hook 'doc-view-mode-hook 'auto-revert-mode)
(autoload 'LilyPond-mode "lilypond-mode" "LilyPond Editing Mode" t)
(add-to-list 'auto-mode-alist '("\\.ly$" . LilyPond-mode))
(add-to-list 'auto-mode-alist '("\\.ily$" . LilyPond-mode))
(add-hook 'LilyPond-mode-hook (lambda () (turn-on-font-lock)))

#+END_SRC

** EMMS configs
#+BEGIN_SRC emacs-lisp
(autoload 'emms-play-directory "emms-source-file" nil t
    (eval-after-load 'emms
      '(progn
	 (require 'emms-setup)
	 (emms-standard)
	 (emms-default-players)
	 (require 'emms-player-mpd)
	 ;; (add-to-list 'emms-info-functions 'emms-info-mpd)
	 ;; (add-to-list 'emms-player-list 'emms-player-mpd)
	 (require 'emms-mode-line)
	 (emms-mode-line 1)
	 (require 'emms-playing-time)
	 (emms-playing-time 1)
	 '(emms-mode-line-mode-line-function (quote emms-mode-line-playlist-current))
	 '(emms-mode-line-titlebar-function (quote ignore))
	 '(emms-playlist-default-major-mode (quote emms-playlist-mode)))))
(global-set-key (kbd "C-c e <up>") 'emms-start)
(global-set-key (kbd "C-c e <down>") 'emms-stop)
(global-set-key (kbd "C-c e <SPC>") 'emms-pause)
(global-set-key (kbd "C-c e <left>") 'emms-previous)
(global-set-key (kbd "C-c e <right>") 'emms-next)
#+END_SRC

** Org configuration
*** Basic org stuff
#+BEGIN_SRC emacs-lisp
(setq org-directory "~/Documents/org/")
(require 'org-install)
(add-to-list 'auto-mode-alist '("\\.org$" . org-mode))
(define-key global-map "\C-cl" 'org-store-link)
(define-key global-map "\C-ca" 'org-agenda)
(setq org-log-done 'time)
(setq org-log-done 'note)
     (defun org-summary-todo (n-done n-not-done)
       "Switch entry to DONE when all subentries are done, to TODO otherwise."
       (let (org-log-done org-log-states)   ; turn off logging
         (org-todo (if (= n-not-done 0) "DONE" "TODO"))))
     (add-hook 'org-after-todo-statistics-hook 'org-summary-todo)
(require 'org-export-as-s5)
#+END_SRC
Mobile Org setup
#+BEGIN_SRC emacs-lisp
(setq org-mobile-inbox-for-pull "~/Documents/org/flagged.org")
(setq org-mobile-directory "~/Dropbox/Documents/org/MobileOrg")
#+END_SRC
*** org-crypt - add :crypt: tag to headline to encrypt text below it
#+BEGIN_SRC emacs-lisp
     (require 'org-crypt)
     (org-crypt-use-before-save-magic)
     (setq org-tags-exclude-from-inheritance (quote ("crypt")))
     
     (setq org-crypt-key nil)
       ;; GPG key to use for encryption
       ;; Either the Key ID or set to nil to use symmetric encryption.
     

     (setq auto-save-default nil)
       ;; Auto-saving does not cooperate with org-crypt.el: so you need
       ;; to turn it off if you plan to use org-crypt.el quite often.
       ;; Otherwise, you'll get an (annoying) message each time you
       ;; start Org.
     
       ;; To turn it off only locally, you can insert this:
       ;;
       ;; # -*- buffer-auto-save-file-name: nil; -*-
#+END_SRC

*** ditaa - make funky ASCII arts within org-mode and convert them to images
Also all the stuff for org-babel

#+BEGIN_SRC emacs-lisp
(setq org-ditaa-jar-path "/home/eddie/.elisp/ditaa-0_9.jar")
(setq ditaa-cmd "java -jar /home/eddie/.elisp/ditaa0_9.jar")
(defun djcb-ditaa-generate ()
  (interactive)
  (shell-command
    (concat ditaa-cmd " " buffer-file-name)))

(add-hook 'org-babel-after-execute-hook 'bh/display-inline-images 'append)

; Make babel results blocks lowercase
(setq org-babel-results-keyword "results")

(defun bh/display-inline-images ()
  (condition-case nil
      (org-display-inline-images)
    (error nil)))

(org-babel-do-load-languages
 (quote org-babel-load-languages)
 (quote ((emacs-lisp . t)
         (dot . t)
         (ditaa . t)
         (python . t)
         (ruby . t)
         (gnuplot . t)
         (clojure . t)
         (sh . t)
         (ledger . t)
         (org . t)
         (plantuml . t)
         (lilypond t)
         (latex . t))))
(setq org-startup-with-inline-images nil)
(add-hook 'org-mode-hook 'auto-revert-mode)
#+END_SRC
** Tree Widgets for things like imenu
#+BEGIN_SRC emacs-lisp
(eval-after-load "tree-widget"
  '(if (boundp 'tree-widget-themes-load-path)
       (add-to-list 'tree-widget-themes-load-path "~/.emacs.d/")))

(autoload 'imenu-tree "imenu-tree" "Imenu tree" t)
(autoload 'tags-tree "tags-tree" "TAGS tree" t)
#+END_SRC

** Modeline configuration, including Nyancat
#+BEGIN_SRC emacs-lisp
(require 'nyan-mode)
;; use setq-default to set it for /all/ modes
(setq-default mode-line-format
	      (list
    ;; the buffer name; the file name as a tool tip
    '(:eval (propertize "%b " 'face 'font-lock-keyword-face
        'help-echo (buffer-file-name)))
    ;;nyan
    '(:eval (list (nyan-create)))
    ;; line and column
    "(" ;; '%02' to set to 2 chars at least; prevents flickering
      (propertize "%02l" 'face 'font-lock-type-face) ","
      (propertize "%02c" 'face 'font-lock-type-face) 
    ") "

    ;; relative position, size of file
    "["
    (propertize "%p" 'face 'font-lock-constant-face) ;; % above top
    "/"
    (propertize "%I" 'face 'font-lock-constant-face) ;; size
    "] "

    ;; the current major mode for the buffer.
    "["

    '(:eval (propertize "%m" 'face 'font-lock-string-face
              'help-echo buffer-file-coding-system))
    "] "


    "[" ;; insert vs overwrite mode, input-method in a tooltip
    '(:eval (propertize (if overwrite-mode "Ovr" "Ins")
              'face 'font-lock-preprocessor-face
              'help-echo (concat "Buffer is in "
                           (if overwrite-mode "overwrite" "insert") " mode")))

    ;; was this buffer modified sincef the last save?
    '(:eval (when (buffer-modified-p)
              (concat ","  (propertize "Mod"
                             'face 'font-lock-warning-face
                             'help-echo "Buffer has been modified"))))

    ;; is this buffer read-only?
    '(:eval (when buffer-read-only
              (concat ","  (propertize "RO"
                             'face 'font-lock-type-face
                             'help-echo "Buffer is read-only"))))  
    "] "

    ;; add the time, with the date and the emacs uptime in the tooltip
    '(:eval (propertize (format-time-string "%H:%M")
              'help-echo
              (concat (format-time-string "%c; ")
                      (emacs-uptime "Uptime:%hh"))))
    " --"

    ;; i don't want to see minor-modes; but if you want, uncomment this:
     minor-mode-alist  ;; list of minor modes
    "%-" ;; fill with '-'
    ))
#+END_SRC

** Some ERC configs
#+BEGIN_SRC emacs-lisp
(autoload 'erc-nick-notify-mode "erc-nick-notify"
  "Minor mode that calls `erc-nick-notify-cmd' when his nick gets
mentioned in an erc channel" t)
(eval-after-load 'erc '(erc-nick-notify-mode t))
    (define-minor-mode ncm-mode "" nil
      (:eval
       (let ((ops 0)
             (voices 0)
             (members 0))
         (maphash (lambda (key value)
                    (when (erc-channel-user-op-p key)
                      (setq ops (1+ ops)))
                    (when (erc-channel-user-voice-p key)
                      (setq voices (1+ voices)))
                    (setq members (1+ members)))
                  erc-channel-users)
         (format " %S/%S/%S" ops voices members))))

(setq erc-timestamp-only-if-changed-flag nil
          erc-timestamp-format "%H:%M "
          erc-fill-prefix "      "
          erc-insert-timestamp-function 'erc-insert-timestamp-left)

(require 'erc-nick-colors)
#+END_SRC

** Email setup
*** GNUs
#+BEGIN_SRC emacs-lisp
(setq gnus-select-method
      '(nnimap "gmail"
	       (nnimap-address "imap.gmail.com")
	       (nnimap-server-port 993)
	       (nnimap-stream ssl)))

(setq message-send-mail-function 'smtpmail-send-it
      smtpmail-starttls-credentials '(("smtp.gmail.com" 587 nil nil))
      smtpmail-auth-credentials '(("smtp.gmail.com" 587
				   "pieceredd@gmail.com" nil))
      smtpmail-default-smtp-server "smtp.gmail.com"
      smtpmail-smtp-server "smtp.gmail.com"
      smtpmail-smtp-service 587
      gnus-ignored-newsgroups "^to\\.\\|^[0-9. ]+\\( \\|$\\)\\|^[\"]\"[#'()]")
#+END_SRC





** Random crap
Small modes that I don't really care about but are a bit o' fun
*** Emacs chess mode settings and other games
#+BEGIN_SRC emacs-lisp
(add-to-list 'load-path "~/.elisp/emacs-chess")
(add-to-list 'load-path "~/.elisp/nummove")
(add-to-list 'load-path "~/.elisp/tronel/")
(autoload 'chess "chess" "Play a game of chess" t)
(autoload 'sudoku "sudoku" "Play a sudoku" t)
(autoload 'mazemax "mazemax" "Find your way out of a maze" t)
(autoload 'mine-sweeper "mine-sweeper" "Play minesweeper" t)
(autoload 'eight-puzzle "eight-puzzle" "Play an eight puzzle" t)
(autoload 'nummove "nummove" "Play a fifteen puzzle" t)
(autoload 'tron "tron" "Play a tron game" t)

#+END_SRC
*** Other small modes
#+BEGIN_SRC emacs-lisp
(autoload 'reddit "reddit" "reddit")
(autoload 'tail "tail" "tail")
(autoload 'pack-windows "~/.elisp/pack-windows" t)
(autoload 'type-test "type-test" "type-test" t)
(setq backup-directory-alist `(("." . "~/.saves")))
(autoload 'tablature-mode "tablature-mode" "tablature-mode" t)
(byte-recompile-directory (expand-file-name "~/.elisp") 0)
(add-hook 'dired-load-hook
          (lambda ()
            (load "dired-x")))

(autoload 'dired-x "dired-x" "dired-x" t)

(require 'uniquify)
(setq 
  uniquify-buffer-name-style 'reverse
  uniquify-separator ":")

(require 'ox-reveal)
(setq org-reveal-root "file:///home/eddie/gits/reveal.js/")

(eval-after-load 'esh-opt
  (progn
    (require 'virtualenvwrapper)
    (venv-initialize-eshell)
    (require 'eshell-prompt-extras)
    (setq eshell-highlight-prompt nil
          eshell-prompt-function 'epe-theme-lambda)))

(add-hook 'eshell-load-hook 'nyan-prompt-enable)

; Make finding file create directory
(defun my-create-non-existent-directory ()
      (let ((parent-directory (file-name-directory buffer-file-name)))
        (when (and (not (file-exists-p parent-directory))
                   (y-or-n-p (format "Directory `%s' does not exist! Create it?" parent-directory)))
          (make-directory parent-directory t))))

(add-to-list 'find-file-not-found-functions #'my-create-non-existent-directory)

(defun on-frame-open (frame)
  (if (not (display-graphic-p frame))
    (set-face-background 'default "unspecified-bg" frame)))
(on-frame-open (selected-frame))
(add-hook 'after-make-frame-functions 'on-frame-open)

(add-hook 'prog-mode-hook 'rainbow-delimiters-mode)

(pdf-tools-install)

(require 'auto-package-update)

(require 'zlc)
(zlc-mode t)
#+END_SRC

*** zone-mode
Zone-Choose allows you to choose certain Zone programs

#+BEGIN_SRC emacs-lisp
(defun zone-choose (pgm)
    "Choose a PGM to run for `zone'."
    (interactive
     (list
      (completing-read
       "Program: "
       (mapcar 'symbol-name zone-programs))))
    (let ((zone-programs (list (intern pgm))))
      (zone)))
#+END_SRC

Use Zone as an X11 locker - requires xtrlock package

#+BEGIN_SRC emacs-lisp
(defun lock-screen ()
   "Lock screen using (zone) and xtrlock
 calls M-x zone on all frames and runs xtrlock"
   (interactive)
   (save-excursion
     ;(shell-command "xtrlock &")
     (set-process-sentinel
      (start-process "xtrlock" nil "xtrlock")
      '(lambda (process event)
         (zone-leave-me-alone)))
     (zone-when-idle 1)))
#+END_SRC
